package bsf.mvc;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by chejiangyi on 2017/4/19.
 * 需要配合HttpContextFilter使用
 */
public class HttpContext {

    private static ThreadLocal<HttpServletRequest> requestContext = new ThreadLocal<HttpServletRequest>();
    private static ThreadLocal<HttpServletResponse> responseContext = new ThreadLocal<HttpServletResponse>();

    public static void init(HttpServletRequest request, HttpServletResponse response) {
        requestContext.set(request);
        responseContext.set(response);
    }

    public static HttpSession getSession() {
        if (getRequest() == null) {
            return null;
        }
        return getRequest().getSession(true);
    }

    public static HttpServletRequest getRequest() {

        HttpServletRequest request = requestContext.get();
        //兼容RequestContextHolder方式
//        if(request == null) {
//            request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        }
        return request;
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse response = responseContext.get();
        //兼容RequestContextHolder方式,可能获取不到，为null
//        if(response == null)
//        {
//            response =  ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
//        }
        return response;
    }
    public static void clear() {
        requestContext.remove();
        responseContext.remove();
    }


    public static HashMap<String, String> getParameterMap() {
        HashMap<String, String> returnMap = new HashMap<>();
        if (getRequest() != null) {
            // 参数Map
            Map properties = getRequest().getParameterMap();
            // 返回值Map
            Iterator entries = properties.entrySet().iterator();
            Map.Entry entry;
            String name = "";
            String value = "";
            while (entries.hasNext()) {
                entry = (Map.Entry) entries.next();
                name = (String) entry.getKey();
                Object valueObj = entry.getValue();
                if (null == valueObj) {
                    value = "";
                } else if (valueObj instanceof String[]) {
                    String[] values = (String[]) valueObj;
                    for (int i = 0; i < values.length; i++) {
                        value = values[i] + ",";
                    }
                    value = value.substring(0, value.length() - 1);
                } else {
                    value = valueObj.toString();
                }
                returnMap.put(name, value);
            }
        }
        return returnMap;
    }
}